package com.solvePlat.service.Impl;

import com.solvePlat.dao.DocumentMapper;
import com.solvePlat.entity.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.Buffer;
import java.util.UUID;

@Service
public class UploadFileDealWithServiceImpl {


    @Value("${uploadDir}")
    private String dir;

    @Resource
    private DocumentMapper documentMapper;

    public Document uploadFileToServer(MultipartFile file, HttpServletRequest request)throws Exception{

            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String originFileName = System.currentTimeMillis() + file.getOriginalFilename();
            String newFileName = UUID.randomUUID().toString();
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
            String destFileName = dir+"uploaded" + File.separator + newFileName+"."+originFileName.split("\\.")[1];
            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
            File destFile = new File(destFileName);

            if (!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }

            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);
             //6.把文件名放在model里，以便后续显示用

            Document document = new Document();
            document.setUuid(UUID.randomUUID().toString());
            document.setPath("uploaded"+File.separator+newFileName+"."+originFileName.split("\\.")[1]);
            document.setType("1");//图片
            document.setFilename(originFileName);
            documentMapper.insert(document);
            return document;
    }

    public BufferedImage getImage(Document document,HttpServletRequest request) throws Exception {

            Document documentDb = documentMapper.selectByPrimaryKey(document.getUuid());
            String destFileName = dir + documentDb.getPath();
            return ImageIO.read(new FileInputStream(destFileName));
    }
}
